//
//  LLFluidViewFlowLayout.m
//  CollectionView使用
//
//  Created by admin on 2019/12/2.
//  Copyright © 2019 LG. All rights reserved.
//

#import "LLFluidViewFlowLayout.h"

@interface LLFluidViewFlowLayout ()

@property (nonatomic, assign) CGFloat margin;

@end

@implementation LLFluidViewFlowLayout

- (void)prepareLayout
{
    [super prepareLayout];
    
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.scrollDirection = UICollectionViewScrollDirectionHorizontal;

    self.margin = (self.collectionView.frame.size.width - self.itemSize.width) * 0.5;
    self.collectionView.contentInset = UIEdgeInsetsMake(0, _margin, 0, _margin);
    
}

/**
   * 当collectionView的显示范围发生改变的时候，是否需要重新刷新布局
   * 一旦重新刷新布局，就会重新调用下面的方法：
   * 1.prepareLayout
   * 2.layoutAttributesForElementsInRect:方法
  */
 - (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
 {
    return YES;
}

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSArray *layoutAttributesArray = [super layoutAttributesForElementsInRect:rect];
    //计算出collectionView的中心的位置
    CGFloat ceterX = self.collectionView.contentOffset.x + self.collectionView.frame.size.width * 0.5;
    
    for (UICollectionViewLayoutAttributes *attr in layoutAttributesArray) {
        // item距离中心点的长度
        CGFloat del = ABS(attr.center.x - ceterX);
        //设置缩放比例
        CGFloat scale = ABS(1 - del / (self.collectionView.frame.size.width * 8));
        //设置cell滚动时候缩放的比例
        attr.transform = CGAffineTransformMakeScale(scale, scale);
    }
    
    
    return layoutAttributesArray;
    
}


///这个方法的返回值，就决定了collectionView停止滚动时的偏移量
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
{
    // 计算出最终显示的矩形框
    CGRect rect;
    rect.origin.y = 0;
    rect.origin.x = proposedContentOffset.x;
    rect.size = self.collectionView.frame.size;

    //获得super已经计算好的布局的属性
    NSArray *arr = [super layoutAttributesForElementsInRect:rect];

    //计算collectionView中心点的x值
    CGFloat centerX = proposedContentOffset.x + self.collectionView.frame.size.width * 0.5;

    CGFloat minDelta = MAXFLOAT;
    for (UICollectionViewLayoutAttributes *attrs in arr) {
        if (ABS(minDelta) > ABS(attrs.center.x - centerX)) {
            minDelta = attrs.center.x - centerX;
        }
    }
    proposedContentOffset.x += minDelta;
    CGFloat index = (proposedContentOffset.x + self.margin - self.sectionInset.left) / (self.itemSize.width + self.minimumLineSpacing);
    if (self.currentIndexBlock) {
        self.currentIndexBlock(index);
    }
    return proposedContentOffset;
}


@end
